<template>
  <el-dialog v-model="visible" :title="formatTitle" width="1200px">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基础设置" name="base">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="6em">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="输入名称" />
          </el-form-item>
          <el-form-item label="开始时间" prop="start_time">
            <el-date-picker v-model="form.start_time" placeholder="选择日期时间" type="datetime" />
          </el-form-item>
          <el-form-item label="结束时间" prop="end_time">
            <el-date-picker v-model="form.end_time" placeholder="选择日期时间" type="datetime" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="添加商品" name="goods">
        <el-button type="primary" @click="goodsVisible = true">添加商品</el-button>
        <el-table
          ref="tableRef"
          :data="selectGoods"
          :load="load"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          default-expand-all
          lazy
          row-key="id"
          @selectionChange="handleSelectionChange"
        >
          <el-table-column :selectable="selectable" type="selection" width="55" />
          <el-table-column label="名称" prop="name" />
          <el-table-column label="活动价格">
            <template #default="{ row }">
              <el-input
                v-if="!row.hasChildren"
                v-model="row.amount"
                placeholder="输入金额"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template #default="{ row }">
              <el-input
                v-if="!row.hasChildren"
                v-model="row.quantity"
                placeholder="输入数量"
                type="number"
              />
            </template>
          </el-table-column>
          <el-table-column label="销售价格" prop="sale_price" />
          <el-table-column label="库存" prop="stock" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <div style="display: flex; justify-content: flex-end; margin-top: 20px">
      <el-button type="primary" @click="handleNext">
        {{ activeName == "base" ? "下一步" : "完成" }}
      </el-button>
    </div>
    <SelectGoods v-model="goodsVisible" :select-list="formatSelectList" @confirm="handleConfirm" />
  </el-dialog>
</template>

<script lang="ts" setup>
import SelectGoods from "@/components/SelectGoods/SelectGoods.vue";
import GoodsAPI from "@/api/goods/goods";
import useActivityGoodsStoreHook from "@/store/modules/goods/activity";
import { cloneDeep } from "lodash-es";

const activityGoodsStore = useActivityGoodsStoreHook();

const visible = defineModel({ type: Boolean });

const props = defineProps({
  type: {
    type: String,
    default: "add",
  },
  currentId: {
    type: [String, Number],
    default: "",
  },
  productList: {
    type: Array,
    default: () => [],
  },
});

const tableRef = ref();

const goodsVisible = ref(false);

const activeName = ref("base");

const formRef = ref();

const defaultForm = {
  name: "",
  start_time: "",
  end_time: "",
  product_list: [],
};

const form = reactive<any>(cloneDeep(defaultForm));

const selectGoods = ref<any>([]);

const formatSelectList = computed(() => {
  return props.productList.map((item: any) => item.id);
});

const rules = {
  name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  start_time: [{ required: true, message: "请输入活动开始时间", trigger: "blur" }],
  end_time: [{ required: true, message: "请输入活动结束时间", trigger: "blur" }],
};

const formatTitle = computed(() => {
  return props.type == "add" ? "添加活动" : "编辑活动";
});

watch(visible, (val) => {
  if (val) {
    if (props.type == "add") {
      Object.assign(form, cloneDeep(defaultForm));
      activeName.value = "base";
    } else if (props.type == "edit") {
      getDetail();
    }
  } else {
    activeName.value = "base";
    selectGoods.value = [];
    Object.assign(form, cloneDeep(defaultForm));
  }
});

async function getDetail() {
  const response: any = await activityGoodsStore.fetchActivityDetail(props.currentId);
  Object.assign(form, response);
  form.product_list = response.products;
  selectGoods.value = response.products.map((item: any) => {
    return {
      name: item.product.name,
      id: item.product.id,
      children: item.skus.map((sku: any) => {
        return {
          id: sku.id,
          variant_id: sku.id,
          name: formatAttr(sku.variant.attributes),
          hasChildren: false,
          stock: sku.variant.stock,
          sale_price: sku.variant.sale_price,
          product_id: item.product.id,
          quantity: sku.quantity,
          amount: sku.amount,
        };
      }),
      hasChildren: true,
    };
  });
  await nextTick();
  selectGoods.value.forEach((item: any) => {
    tableRef.value!.toggleRowSelection(item, undefined, false);
  });
}

function selectable(row: any) {
  return !row.hasChildren;
}

function handleClick(tab: any) {
  activeName.value = tab.props.name;
}

function handleSelectionChange(e: any) {
  form.product_list = e;
}

function handleNext() {
  if (activeName.value === "base") {
    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        activeName.value = "goods";
      } else {
        return false;
      }
    });
  } else if (activeName.value === "goods") {
    activityGoodsStore.fetchAddActivity(form).then(() => {
      visible.value = false;
    });
  }
}

function handleConfirm(e: any[]) {
  selectGoods.value = e.map((i) => ({ ...i, children: [], hasChildren: true }));
}

function formatAttr(attr: any[]) {
  return attr.map((i) => `${i.key}:${i.value}`).join(";");
}

const load = async (row: any, treeNode: unknown, resolve: (data: any[]) => void) => {
  if (row.children.length > 0) {
    return resolve(row.children);
  }
  const response: any = await GoodsAPI.getGoodsDetail(row.id);
  resolve(
    response.skus.map((i: any) => ({
      id: i.id,
      variant_id: i.id,
      name: formatAttr(i.attributes),
      hasChildren: false,
      stock: i.stock,
      sale_price: i.sale_price,
      product_id: i.product.id,
      quantity: 0,
      amount: 0,
    }))
  );
};
</script>

<style lang="scss" scoped></style>
